package org.ghost.parallel.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreTest {
    private final Logger logger = LoggerFactory.getLogger(SemaphoreTest.class);
    /**
     * 设置最多同时有几个线程执行acquire与release之间的代码
     */
    private static Semaphore semaphore = new Semaphore(3, true);
    private int sum = 0;

    public void addLock(int val) {
        try {
            //从信号量中获取一个许可
            semaphore.acquire();

            sum += val;

            //释放许可，将占有的信号量归还
            semaphore.release();

            logger.info("*****sum={}", sum);
        } catch (InterruptedException e) {
            logger.error("*****addLock出现异常,sum={},{}", sum, e);
        }
    }

    public void addTryLock(int val) {
        try {
            if (semaphore.tryAcquire(1L, TimeUnit.SECONDS)) {
                sum += val;

                semaphore.release();

                logger.info("*****sum={}", sum);
            } else {
                logger.info("*****获取准入许可失败,sum={}", sum);
            }
        } catch (InterruptedException e) {
            logger.error("*****addLock出现异常,sum={},{}", sum, e);
        }
    }

    public void add(int val) {
        sum += val;
        logger.info("*****sum={}", sum);
    }

    public void printSum() {
        logger.info("*****final result:{}", sum);
    }
}
